/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is ThumbsDown.
 *
 * The Initial Developer of the Original Code is
 * Atte Kemppilä.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 * 
 * ***** END LICENSE BLOCK ***** */


function WrappedPage() // extend WizardPage
{
    var depends = "images script";
    WizardPage.call(this, depends);
}

WrappedPage.prototype =
{
    onPageShow: function()
    {
        let self = this;
        
        if (this.firstRun)
        {
            this.$name = document.getElementById("mlist_wrapped_name");
            this.$value = document.getElementById("tbox_wrapped_value");
            this.$valueResetDefault = document.getElementById("btn_wrapped_value_resetDefault");
            this.$valueResetScript = document.getElementById("btn_wrapped_value_resetScript");
            this.$valueHead = document.getElementById("lhead_wrapped_values");
            this.$valueList = document.getElementById("rlbox_wrapped_values");
        }
        
        if (this.dirty.images || this.dirty.script)
        {
            this.entries =
                scriptWizard.getEntries({
                    thumbnail: model.selected,
                    linkUrl: model.linkUrls,
                    image: model.images,
                });
            
            let script = null;
            if (model.script && (model.script.type == "wrapped"))
                script = model.script;
            
            // resolve all available attribute names
            let nameSet = {};
            if (script)
                nameSet[script.attrName] = true;
            for each (let entry in this.entries)
            {
                let attrs = entry.image.attributes;
                for (let i = 0; i < attrs.length; i++)
                    nameSet[attrs[i].name] = true;
            }
            this.names = [name for (name in nameSet)];
            this.names.sort();
            
            // resolve value regexps
            this.value = {};
            for each (let name in this.names)
            {
                this.value[name] = {};
                
                if (name == "src")
                {
                    // new script url attr regexp
                    let urls = [entry.image.getAttribute(name) for each (entry in this.entries)];
                    let urlTokens = scriptWizard.getUrlTokens(urls);
                    this.value[name].default = scriptWizard.resolveUrlRegExp(urlTokens);
                }
                else
                {
                    // new script non-url attr regexp
                    let values = [entry.image.getAttribute(name) for each (entry in this.entries)];
                    this.value[name].default = scriptWizard.resolveRegExp(new StringArray(values));
                }
                
                // existing script attr regexp
                this.value[name].script = ((script && (name == script.attrName)) ? script.attrValue.pattern : "");
                
                this.value[name].value = this.value[name].script || this.value[name].default;
            }
            
            this._updateNameList();
            
            // $name set triggers select event -> onNameSelect()
            if (script)
                this.$name.value = script.attrName;
            else if (("id" in this.value) && /^[-\w]+$/.test(this.value["id"].value))
                this.$name.value = "id";
            else
                this.$name.value = "src";
            
            this.$valueResetScript.hidden = (! script);
        }
    },
    
    onNameSelect: function()
    {
        let name = this.$name.value;
        this.$value.value = this.value[name].value;
        
        this._updateValueList();
        this._updateValue();
        this._updateButtons();
        wizard.updateWizardButtons();
    },
    
    onValueInput: function()
    {
        let name = this.$name.value;
        this.value[name].value = this.$value.value;
        
        // update buttons immediately so that textbox content and buttons are in sync
        this._updateButtons();
        // canAdvance() depends on textbox's timer
        callLater(0, null, function() { wizard.updateWizardButtons() });
    },
    
    onValueCommand: function()
    {
        if (page != pages["wrapped"])
            return;
        
        this._updateButtons();
        this._updateValue();
        wizard.updateWizardButtons();
    },
    
    resetValue: function(source)
    {
        let name = this.$name.value;
        this.$value.value = this.value[name].value = this.value[name][source];
        
        this._updateButtons();
        this._updateValue();
        wizard.updateWizardButtons();
    },
    
    _updateNameList: function()
    {
        this.$name.removeAllItems();
        
        for each (let name in this.names)
            this.$name.appendItem(name, name);
    },
    
    _updateButtons: function()
    {
        let name = this.$name.value;
        this.$valueResetDefault.disabled = (this.$value.value == this.value[name].default);
        this.$valueResetScript.disabled = ((! this.value[name].script) || (this.$value.value == this.value[name].script));
    },
    
    _updateValue: function()
    {
        let pattern = "^" + this.$value.value + "$"
        this.$valueList.pattern = pattern;
    },
    
    _updateValueList: function()
    {
        let name = this.$name.value;
        
        this.$valueHead.label = name;
        
        while (this.$valueList.itemCount > 0)
            this.$valueList.removeItemAt(0);
        for each (let entry in this.entries)
            this.$valueList.appendItem(entry.image.getAttribute(name));
    },
    
    canAdvance: function()
    {
        // textbox input is pending
        if (this.$value._timer)
            return false;
        
        if (! this.$value.value)
            return false;
        
        if (! this.$valueList.match)
            return false;
        
        return true;
    },
    
    onPageAdvanced: function()
    {
        model.type = "wrapped";
        model.attrName = this.$name.value;
        model.attrValue = this.$value.value;
        return wizard.advance("script");
    }
}

extend(WrappedPage, WizardPage);

pages["wrapped"] = new WrappedPage();
